﻿using Ebusiness_Framework.DistributedTransaction;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ebusiness_Framework.DistributedAuthorization
{
    /// <summary>
    /// 分布式鉴权
    /// </summary>
    public static class DistributedAuthorizationServiceCollectionExtentions
    {
        public static IServiceCollection UseDistributedAuthorization(this IServiceCollection services, IConfiguration configuration)
        {
            DistributedAuthorizationOptions distributedAuthorizationOptions = configuration.GetSection("DistributedAuthorization").Get<DistributedAuthorizationOptions>();
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                 .AddJwtBearer(options =>
                 {
                     options.Authority = distributedAuthorizationOptions.Authority;
                     options.Audience = distributedAuthorizationOptions.Audience;
                     //options.RequireHttpsMetadata = false; // 如果你没配 HTTPS，必须关掉
                     //options.TokenValidationParameters = new TokenValidationParameters
                     //{
                     //    ValidateIssuer = true,
                     //    ValidIssuer = "https://20.2.26.26:44392/",
                     //};

                     // 忽略 HTTPS 证书验证（开发环境使用）
                     options.BackchannelHttpHandler = new HttpClientHandler
                     {
                         ServerCertificateCustomValidationCallback =
                             HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                     };
                 });
            return services;
        }
    }
}
